#!/usr/bin/perl -wT
use CGI qw(:standard);
use CGI::Carp qw(fatalsToBrowser);
use File::Basename;
use POSIX ('strftime');

use strict;

my $galleryURI = "http://i72.photobucket.com/albums/i171/captain_only";
my $homeDirectory = dirname($ENV{'SCRIPT_FILENAME'});

print header("application/javascript");

if( param("Target") =~ /\/(Photos.*)\/([0-9]{8}-[0-9]{6})-001\.jpg/ )
{
    my $dir = $1;
    my $item = $2;
    my $filebase = "$homeDirectory/$dir/$item";
    
    my $caption;
    my $description = "";
    
    if( -e "$filebase.txt" )
    {
        open(CAPTIONFILE, "$filebase.txt");
        $caption = <CAPTIONFILE>;
        <CAPTIONFILE>;
        while(<CAPTIONFILE>) {$description = $description . $_;}
        close(CAPTIONFILE);
        
        $caption =~ s/\s*$//g;
        $caption =~ s/&/&amp;/g;
        $caption =~ s/'/\\'/g;
        
        if( $description )
        {
            $description =~ s/\s*$//g;
            $description =~ s/&/&amp;/g;
            $description =~ s/'/\\'/g;
            $description =~ s/\n//g;
            $description =~ s/\r//g;
        }
    }
    else
    {
        $caption = $description = $item;
    }

    print "document.getElementById(\"caption\").innerHTML = '$caption';";
    print "document.getElementById(\"description\").innerHTML = '$description';";
    print "document.getElementById(\"item\").innerHTML = '";

    if( -e "$filebase.jpg" )
    {
        my @stats = stat("$filebase.jpg");

        print img {
            src => "$galleryURI/$dir/$item.jpg",
            alt => $caption,
            title => strftime("%Y-%m-%d", localtime($stats[9]))
        };
    }
    elsif( -e "$filebase.avi" ||  -e "$filebase.mp4" ||  -e "$filebase.wmv" )
    {
        print embed {
            width => "430",
            height => "389",
            type => "application/x-shockwave-flash",
            wmode => "transparent",
            src => "http://s72.photobucket.com/player.swf?file=http://vid72.photobucket.com/albums/i171/captain_only/Movies/$item.flv"
        };
    }
    elsif( -e "$filebase.mp3" )
    {
        print embed {
            src => "http://kabal.no-ip.org/~erik/Isabel/$dir/$item.mp3"
        };
    }

    print "';";
}
